package chapter11.section3;

/*程序11-2e CLerk 模拟银行职员*/

import java.util.Random;

public class Clerk extends Thread {
    private final QueueMachine queue;// 排队机的引用
    private final String name;

    public Clerk(QueueMachine queue, String name) {
        super(name);
        this.queue = queue;
        this.name = name;
    }

    public Clerk(QueueMachine queue, String name, ThreadGroup group) {
        super(group, name);// 将当前线程添加到一个指定的线程组内
        this.queue = queue;
        this.name = name;
    }

    @Override
    public void run() {
        Random rand = new Random();
        Transaction tran = null;
        String working = "woring";
        while (!working.equals("closed") || (!queue.isEmpty())) {
            tran = queue.get();
            /*
             * 如果没有得到业务，则休息，在休息的过程中，如果得到中断通知， 则设置结束工作状态
             */
            if (tran == null) {
                try {
                    Thread.sleep(rand.nextInt(200 + rand.nextInt(3)));
                } catch (InterruptedException e) {
                    if (queue.isEmpty()) {
                        working = "closed";
                    }
                }
                continue;
            }
            System.out.println(this.name + "得到业务:" + tran);
            int newBalance = 0;// 记录业务完成后的新余额
            if (tran.getTranType().compareTo(Transaction.DEPOSIT) == 0) {
                newBalance = tran.getAccount().getBalance() + tran.getAmount();
            } else if (tran.getTranType().equals(Transaction.WITHDRAW)) {
                newBalance = tran.getAccount().getBalance() - tran.getAmount();
            }
            /*
             * 下面利用线程休眠控制每笔业务处理的时间长短不一，故意造成不同职员之间 的工作不同步，以便展示可能出现的问题，如果休眠时被中断，则判断排队机中
             * 是否还有业务等待完成，没有的话，设置工作结束变量，退出循环，结束线程执行
             */
            try {
                Thread.sleep(rand.nextInt(200 + rand.nextInt(3)));
            } catch (InterruptedException e) {
                if (queue.isEmpty()) {
                    working = "closed";
                }
            }
            tran.getAccount().setBalance(newBalance);// 休眠后，更新账户余额
            System.out.printf(this.name + "完成%d号业务处理，处理后账户余额是%d\r\n", tran.getNum(), newBalance);
        }
    }
}